package com.ruoyi.project.app.interfaces;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Random;

/**
 * 旷视API
 */
public interface FaceApiInterface {
    // SETTING
    String apiKey = "xb7fKg-O8dW4nLaCvBi8xVjb9B9xxu6Q";// 文档密钥
    String apiSecret = "eK-oJbfG7TICP67iZmJNDRtYdS1NZdz_";  // 安全密钥
    String signVersion = "hmac_sha1"; // 签名版本
    long expired = 10000L; // 有效时间100秒

    /**
     * 生成签名
     *
     * @return sign 签名结果
     * @throws Exception 签名异常
     */
    default String createSign() throws Exception {
        return createSign(apiKey, apiSecret, expired);
    }

    /**
     * 生成签名
     *
     * @param apiKey    文档密钥
     * @param apiSecret 安全密钥
     * @param expired   有效时间
     * @return sign 签名结果
     * @throws Exception 签名异常
     */
    default String createSign(String apiKey, String apiSecret, long expired) throws Exception {
        long now = System.currentTimeMillis() / 1000;
        int rdm = Math.abs(new Random().nextInt());
        // 生成 hmacSha1 签名 - start
        String plainText = String.format("a=%s&b=%d&c=%d&d=%d", apiKey, now + expired, now, rdm);
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec secretKey = new SecretKeySpec(apiSecret.getBytes(), "HmacSHA1");
        mac.init(secretKey);
        byte[] hmacDigest = mac.doFinal(plainText.getBytes());
        // 生成 hmacSha1 签名 - end
        byte[] signContent = new byte[hmacDigest.length + plainText.getBytes().length];
        System.arraycopy(hmacDigest, 0, signContent, 0, hmacDigest.length);
        System.arraycopy(plainText.getBytes(), 0, signContent, hmacDigest.length, plainText.getBytes().length);
        // 生成 base64 编码
        return Base64.getEncoder().encodeToString(signContent);
    }
}
